package com.whoyx.jiebing.domain.msg.resp;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.whoyx.jiebing.dao.entity.MsgRecordEntity;
import com.whoyx.jiebing.domain.msg.MsgBody;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MsgDataRespDto {
    /**
     * 发送方uid
     */
    private String fromUid;

    /**
     * 接收方uid
     */
    private String toUid;

    /**
     * 消息时间
     */
    private String msgTime;

    /**
     * 消息内容
     */
    private List<MsgBody> msgBody;

    /**
     * 自定义消息
     */
    private String cloudCustomData;

    public static MsgDataRespDto buildWithEntity(MsgRecordEntity entity) {
        String msgTime;
        if (LocalDate.now().atStartOfDay().isBefore(entity.getMsgTime())
                || LocalDate.now().atStartOfDay().equals(entity.getMsgTime())) {
            if (LocalDate.now().atStartOfDay().plusHours(12).isAfter(entity.getMsgTime())) {
                msgTime = "上午" + LocalDateTimeUtil.format(entity.getMsgTime(), "HH:mm");
            } else {
                msgTime = "下午" + LocalDateTimeUtil.format(entity.getMsgTime(), DatePattern.NORM_TIME_PATTERN);
            }
        } else if (LocalDate.now().minusDays(1).atStartOfDay().isBefore(entity.getMsgTime())
                || LocalDate.now().minusDays(1).atStartOfDay().equals(entity.getMsgTime())) {
            if (LocalDate.now().atStartOfDay().plusHours(12).isAfter(entity.getMsgTime())) {
                msgTime = "昨天上午" + LocalDateTimeUtil.format(entity.getMsgTime(), DatePattern.NORM_TIME_PATTERN);
            } else {
                msgTime = "昨天下午" + LocalDateTimeUtil.format(entity.getMsgTime(), DatePattern.NORM_TIME_PATTERN);
            }
        } else {
            msgTime = LocalDateTimeUtil.format(entity.getMsgTime(), DatePattern.NORM_DATE_PATTERN);
        }


        return MsgDataRespDto.builder()
                .msgTime(msgTime)
                .fromUid(entity.getFromUid())
                .toUid(entity.getToUid())
                .msgBody(JSONUtil.toList(entity.getMsgBody(), MsgBody.class))
                .cloudCustomData(entity.getCloudCustomData())
                .build();
    }
}
